1
Lesson 5: Code Reuse with Functions (Introduction)
EvoClass-AI001 Lecture 5
00:00

Lesson 5: Code Reuse with Functions (Introduction)

Functions are named, self-contained blocks of organized, reusable code designed to perform a single, related action. They are the fundamental tool for achieving modularity in programming, allowing complex systems to be broken down into smaller, manageable units.

1. The Power of Code Reuse

The defining benefit of functions is the ability to write a piece of logic once and execute it hundreds of times without copying and pasting. This reduces errors, improves efficiency, and makes large applications easier to maintain and scale. This principle is often referred to as DRY (Don't Repeat Yourself).

This lesson focuses on mastering the structure of defining a function, passing input information (arguments), and managing output results. We will use functions to abstract complex mathematical operations, such as calculating the area of a circle $A = \pi r^2$, using reusable logic.

2. Defining and Calling Functions

  • Definition: Functions are created using the def keyword, followed by the function name and parentheses.
  • Parameters: These are variables listed inside the function's parentheses, acting as placeholders for input values (arguments) that the function needs to execute its task.
  • Invocation (Calling): To execute a function, you simply write its name followed by parentheses, passing the required arguments.
💡 Indentation is Non-Negotiable
All code belonging to the function body must be indented (usually four spaces). Python uses this indentation, following the colon after the def statement, to determine exactly where the function block begins and ends.
main.py
1
# main.py - Function Definition
2
3
def add_numbers(a, b):
4
    # This function calculates the sum of a and b
5
    result = a + b
6
    return result
7
8
# Call the function and store the output
9
num1 = 10
10
num2 = 5
11
sum_result = add_numbers(num1, num2)
12
13
# Display the final result
14
print(f"The sum is: {sum_result}")
TERMINAL bash — 80x24
> Ready. Click "Run" to execute.
>